package com.example.demo.elasticsearch.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ES基于6.2.4版本
 * @author: htc
 * @date: Created in 14:49 2018/12/29.
 */
//@Configuration
public class ElasticSearchConfig {
//    @Bean
//    public TransportClient esClient() throws UnknownHostException {
//        //初始化配置
//        Settings settings = Settings.builder()
//                .put("cluster.name", "htc")
//                //增加嗅探机制，找到ES集群
//                .put("client.transport.sniff", true)
//                .build();
//
//        //初始化master节点
//        InetSocketTransportAddress master = new InetSocketTransportAddress(
//                InetAddress.getByName("127.0.0.1"),
//                //TCP端口
//                9300
//        );
//
//        TransportClient client = new PreBuiltTransportClient(settings);
//        //将节点加入集群
//        client.addTransportAddress(master);
//        return client;
//    }

    @Bean
    public TransportClient client() throws UnknownHostException {

        //es集群连接
        TransportAddress node = new TransportAddress(
                InetAddress.getByName("localhost"),
                9300
        );

        //es集群配置（自定义配置） 连接自己安装的集群名称
        Settings settings = Settings.builder()
                .put("cluster.name","htc")
                .put("client.transport.sniff", true)
                .build();

        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);

        client.addTransportAddress(node);

        return client;
    }
}
